//
//  DBHelper+Reading.m
//  KidReading
//
//  Created by Telen on 16/4/10.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "DBHelper+Reading.h"
#include "ConstDefine.h"

@implementation TABLE_READ_RECORD
+ (NSString*)tableName{return @"read_record";}
+ (NSString *)primaryKey{return @"primary key(enterTime)";};
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" enterTime=%lld",_enterTime];}
@end

@implementation TABLE_READ_RECORD_DICT
+ (NSString*)tableName{return @"read_record_dict";}
+ (NSString *)primaryKey{return @"primary key(createtime,remarks)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" createtime='%@' and remarks = '%@'",@(_createtime),_remarks];}
@end

@implementation TABLE_READ_OVER

+ (NSString*)tableName{return @"read_over";}
+ (NSString *)primaryKey{return @"primary key(userId,bookId,pageIndex)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" userId='%@' and bookId='%@' and pageIndex='%@'",@(_userId),@(_bookId),@(_pageIndex)];}

@end

@implementation TABLE_TALK_SAVE_INFO
+ (NSString *)tableName{return @"talk_save_info";}
+ (NSString *)primaryKey{return @"primary key(talkVideoUrl)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" talkVideoUrl=%@",_talkVideoUrl];}
@end

#pragma mark
@implementation DBHelper (Reading)
ASSOCIATED(dbQue_Record, setDbQue_Record, JRFMDatabaseQueue*, OBJC_ASSOCIATION_RETAIN_NONATOMIC)

+ (void)load{
    [self swizzleSelector:@selector(init) withSelector:@selector(init_Reading)];
}

- (void)update_VersionForRecordDB:(JRFMDatabase*)db
{
    long ver = [JRFMDatabase JRFMDB_getVersionFromDB:db];
    if (ver <= 0) {
        [JRFMDatabase JRFMDB_setDB:db version:2];//Version 3.0.0开发使用 //1->2.0.1
    }
}

- (instancetype)init_Reading
{
    self = [self init_Reading];
    if (self) {
        BOOL debugDB = YES;
#if __KeyForDB_ON_
        debugDB = NO;
#endif
        NSString* path = [self getDBPath:__DBFileName_record debugPath:__DBFileName_record_debug dbKey:__KeyForDB_ dbebug:debugDB];
        [self dbFile_initForDBPath:path];
        self.dbQue_Record = [JRFMDatabaseQueue databaseQueueWithPath:path];
        [self.dbQue_Record inDatabase:^(JRFMDatabase *db) {
#if __KeyForDB_ON_
            if (![db setKey:__KeyForDB_]) {
                NSLog(@"setkey failed");
            };
#endif
            //
            [db executeUpdate:[TABLE_READ_RECORD createTable]];
            [db executeUpdate:[TABLE_READ_RECORD_DICT createTable]];
            [db executeUpdate:[TABLE_READ_OVER createTable]];
            //
            [db executeUpdate:[TABLE_TALK_SAVE_INFO createTable]];
            //
            [self update_VersionForRecordDB:db];
        }];
        //
    }
    return self;
}
//
//
- (void)readOver_updateListToTableClass:(NSString *)tableClassName dictArr:(NSArray*)dictList complete:(void (^)(void))comp{
    [DataProcess do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self updateListToTableClass:tableClassName dictArr:dictList db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
//
- (void)readOver_deletListToTableClass:(NSString *)tableClassName dictArr:(NSArray*)dictList complete:(void (^)(void))comp{
    [DataProcess do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self deletListToTableClass:tableClassName dictArr:dictList db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)readOver_deletListToTableClass:(NSString *)tableClassName tbArr:(NSArray*)dictList complete:(void (^)(void))comp{
    [DataProcess do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self deletListToTableClass:tableClassName tbArr:dictList db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
//
- (void)readOver_getDictList:(void(^)(NSArray* list))retlist fromTableClass:(NSString*)tableClassName where:(NSString*)wheresql{
    [DataProcess do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSArray * arr = [self getDictList_fromTableClass:tableClassName where:wheresql db:db];
            [DataProcess do_Main_quick:^{
                retlist(arr);
            }];
        }];
    }];
}
- (void)readOver_getList:(void(^)(NSArray* list))retlist fromTableClass:(NSString*)tableClassName where:(NSString*)wheresql{
    [self readOver_getDictList:^(NSArray *list) {
        [DataProcess do_Async_quick:^{
            NSMutableArray* marr = [NSMutableArray new];
            [list enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
                id obj = [NSClassFromString(tableClassName) JRMJ_objectWithKeyValues:dict];
                if ([obj isKindOfClass:[TABLE_base class]]) {
                    NSDictionary* replaceKeys = [[obj class] replacedKeyFromPropertyName];
                    for (NSString* key in replaceKeys) {
                        id value = dict[key];
                        if (value && [obj hasProperty:key]) {
                            [obj setValue:value forKey:key];
                        }
                    }
                }
                if (obj) {
                    [marr addObject:obj];
                }
            }];
            [DataProcess do_Main_quick:^{
                retlist(marr);
            }];
        }];
    } fromTableClass:tableClassName where:wheresql];
}

@end
